<template>
  <div class="app-container" id="userContainer">
    <div style="margin-bottom: 30px">
      <el-row :gutter="20">
        <el-col :span="5">
          <el-input
            placeholder="用户名..."
            v-model="queryForm.query"
            clearable
            @keyup.enter="initUserList(1)"
          ></el-input>
        </el-col>
        <el-button
          type="primary"
          :icon="Search"
          @click="initUserList(1)"
          v-hasPerm="['system:user:query']"
          >搜索</el-button
        >
        <el-button
          type="success"
          :icon="DocumentAdd"
          @click="saveSysUserHandler(-1)"
          v-hasPerm="['system:user:add']"
          >新增</el-button
        >
        <!-- <el-button
        type="warning"
        :icon="DocumentAdd"
        @click="exportSysUserHandler"
        v-hasPerm="['system:user:export']"
        >导出</el-button
      > -->
        <el-popconfirm
          title="您确定批量删除这些记录吗？"
          @confirm="handleDelete(null)"
        >
          <template #reference>
            <el-button
              type="danger"
              :icon="Delete"
              :disabled="delBtnStatus"
              v-hasPerm="['system:user:delete']"
              >批量删除</el-button
            >
          </template>
        </el-popconfirm>
        <el-button @click="resetForm" :icon="Refresh">重置</el-button>
      </el-row>
    </div>
    <el-table
      :data="tableData"
      stripe
      style="width: 100%"
      :row-style="{ height: '40px' }"
      :cell-style="{ padding: '0px' }"
      @selection-change="handleSelectionChange"
      row-class-name="table-row-cls"
    >
      <el-table-column
        type="selection"
        width="55"
        :selectable="tableRowHandle"
      />
      <el-table-column label="头像" prop="avatar" width="80" align="center">
        <template v-slot="scope">
          <img
            width="40"
            :src="pre_url + '/image/userAvatar/' + scope.row.avatar"
            alt=""
          />
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户" align="center" />
      <el-table-column
        prop="email"
        label="邮箱"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column prop="phone" label="手机号" align="center" />
      <el-table-column prop="status" label="状态" align="center">
        <template v-slot="{ row }">
          <el-switch
            v-model="row.status"
            @change="statusChangeHandle(row)"
            active-value="0"
            inactive-value="1"
            size="small"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        align="center"
        width="180"
      />
      <el-table-column prop="action" label="操作" width="150" align="center">
        <template v-slot="scope">
          <div style="display: flex; align-items: center">
            <el-button
              type="primary"
              :icon="Edit"
              @click="saveSysUserHandler(scope.row.id)"
              v-hasPerm="['system:user:edit']"
              size="small"
              text
              v-if='!scope.row.isAdmin'
              >编辑</el-button
            >
            <el-dropdown
              size="small"
              @command="(command) => handleCommand(command, scope.row)"
              v-hasPerm="['system:user:resetPwd', 'system:user:role']"
              v-if='!scope.row.isAdmin'
            >
              <el-button size="small" type="text"
                >更多<el-icon><DArrowRight /></el-icon
              ></el-button>
              >
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-hasPerm="['system:user:resetPwd']"
                    command="handleResetPwd"
                  >
                    <el-button
                      type="warning"
                      :icon="RefreshRight"
                      size="small"
                      text
                      >重置密码</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-hasPerm="['system:user:role']"
                    command="handleAuthRole"
                  >
                    <el-button type="primary" :icon="Tools" size="small" text
                      >分配角色</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-hasPerm="['system:user:delete']"
                    command="handleDelete"
                  >
                    <el-button
                      v-if="
                        scope.row.sysRoleList.some((item) => item.id == 1)
                          ? false
                          : true
                      "
                      type="danger"
                      :icon="Delete"
                      v-hasPerm="['system:user:delete']"
                      size="small"
                      text
                      >删除</el-button
                    >
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="queryForm.pageNum"
        v-model:page-size="queryForm.pageSize"
        :page-sizes="[5, 10, 20, 50, 100]"
        :small="false"
        :disabled="false"
        :background="false"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <user-dialog
      v-model="dialogVisible"
      :userId="userId"
      :dialogTitle="dialogTitle"
      :dialogVisible="dialogVisible"
      @initUserList="initUserList"
    />
    <role-dialog
      v-model="roleDialogVisible"
      :sysRoleList="sysRoleList"
      :roleDialogVisible="roleDialogVisible"
      :id="userId"
      @initUserList="initUserList"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getUserList,
  updateUserStatus,
  deleteUser,
  resetPwd,
} from "@/api/user";
import {
  DArrowRight,
  Delete,
  DocumentAdd,
  Edit,
  RefreshRight,
  Search,
  Tools,
  Refresh
} from "@element-plus/icons-vue";

import UserDialog from "./components/UserDialog.vue";
import RoleDialog from "./components/RoleDialog.vue";

const tableData = ref([]);
const total = ref(0);
const pre_url = ref(import.meta.env.VITE_APP_WEB_API);
const queryForm = ref({
  query: "",
  pageNum: 1,
  pageSize: 5,
});
const dialogVisible = ref(false);
const userId = ref(-1);
const dialogTitle = ref("");
const delBtnStatus = ref(true);
const multipleSelection = ref([]);
const roleDialogVisible = ref(false);
const sysRoleList = ref([]);

const handleRoleDialogValue = (row) => {
  userId.value = row.id;
  sysRoleList.value = row.sysRoleList;
  roleDialogVisible.value = true;
};
const tableRowHandle = (row) => {
  const sysRoleList = row.sysRoleList;
  if (sysRoleList.length) {
    if (sysRoleList.some((item) => item.id == 1)) {
      return false;
    } else {
      return true;
    }
  } else {
    return true;
  }
};
const handleCommand = (command, row) => {
  switch (command) {
    case "handleResetPwd":
      resetPwdHandler(row.id);
      break;
    case "handleAuthRole":
      handleRoleDialogValue(row);
      break;
    case "handleDelete":
      handleDelete(row);
      break;
    default:
      break;
  }
};
//新增用户
const saveSysUserHandler = (uid) => {
  if (uid > 0) {
    userId.value = uid;
    dialogTitle.value = "编辑用户";
  } else {
    userId.value = -1;
    dialogTitle.value = "新增用户";
  }
  dialogVisible.value = true;
};
const resetForm = () => {
  queryForm.value = {
    query: "",
    pageNum: 1,
    pageSize: 5,
  };
  initUserList(1);
};
const initUserList = async (pageNum?: number) => {
  if (pageNum) queryForm.value.pageNum = pageNum;
  let result = await getUserList(queryForm.value);
  let res = result.data;
  if (res.code == 200) {
    res.data.userList.map((m) => {
      m.rolesStr = m.sysRoleList.map((t:any) => t.name).join(",");
      m.isAdmin=m.sysRoleList.some((t:any)=>t.id==1)
      return m;
    });
    tableData.value = res.data.userList;
    total.value = res.data.total;
  }
};

const handleSizeChange = (val) => {
  queryForm.value.pageSize = val;
  console.log("queryForm", queryForm);
  initUserList();
};
const handleCurrentChange = (val) => {
  queryForm.value.pageNum = val;
  initUserList();
};

/**
 * 更新用户状态
 */

const statusChangeHandle = async (row) => {
  const res = await updateUserStatus(row);
  const data = res.data;
  if (data.code == 200) {
    if (row.status == 0) {
      ElMessage({
        type: "success",
        message: "启用用户成功",
      });
    } else {
      ElMessage({
        type: "success",
        message: "禁用用户成功",
      });
    }
  } else {
    ElMessage({
      type: "error",
      message: data.msg,
    });
  }
};
const handleSelectionChange = (selection) => {
  // 有选择项才有批量删除
  if (selection.length > 0) delBtnStatus.value = false;
  else delBtnStatus.value = true;
  multipleSelection.value = selection;
};

const handleDelete = async (row: any) => {
  ElMessageBox.confirm("您确定要删除这个记录吗?", "信息", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      var userList: Array<Object> = [];
      if (row) {
        userList.push(row);
      } else {
        multipleSelection.value.forEach((row: any) => {
          if (row.id != 1) userList.push(row);
        });
      }
      const res = await deleteUser(userList);
      const data = res.data;
      if (data.code == 200) {
        ElMessage({
          type: "success",
          message: data.msg,
        });
        initUserList(1);
      } else {
        ElMessage({
          type: "error",
          message: data.msg,
        });
      }
    })
    .catch(() => {});
};
const resetPwdHandler = async (id) => {
  ElMessageBox.confirm("您确定要重置密码吗?", "信息", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await resetPwd(id);
      const data = res.data;
      if (data.code == 200) {
        ElMessage({
          type: "success",
          message: data.msg,
        });
      } else {
        ElMessage({
          type: "error",
          message: data.msg,
        });
      }
    })
    .catch(() => {});
};
onMounted(() => {
  initUserList();
});
</script>

<style lang="less" scoped>
.app-container {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
.header {
  padding-bottom: 16px;
  box-sizing: border-box;
}

.el-pagination {
  float: right;
  padding: 20px;
  box-sizing: border-box;
}

.el-table__cell {
  word-break: break-word;
  height: 40px;
  font-size: 13px;
}

.el-tag--small {
  margin-left: 5px;
}
</style>
<style lang="less">
.table-row-cls {
  .el-button + .el-button {
    margin-left: 0;
  }
}
</style>